function func(p, fn, params) {
    try {
        // 初始化返回结果结构
        let result = {
            list: [],
            page: params.page || 1,
            pagecount: 1,
            limit: 20,
            total: 0
        };

        // 根据参数类型执行不同操作
        if (params.action === "category") {
            result = handleCategories(p);
        } else if (params.action === "list") {
            result = handleVideoList(p, params);
        } else if (params.action === "play") {
            // 处理播放地址，新增线路选择和参数配置
            result = handlePlayUrl(p, params);
        } else if (params.action === "search") {
            result = handleSearch(p, params);
        } else if (params.action === "playbackInfo") {
            // 新增：获取播放详情（如剧集列表）
            result = handlePlaybackInfo(p, params);
        }

        fn(result);
    } catch (e) {
        fn({
            error: "处理失败: " + e.message,
            stack: e.stack || "",
            retry: true  // 新增：标记是否可重试
        });
    }
}

// 处理分类列表（保持不变）
function handleCategories(p) {
    const doc = new DOMParser().parseFromString(p, "text/html");
    const categories = [];
    
    doc.querySelectorAll(".category-item").forEach(item => {
        categories.push({
            type_id: item.getAttribute("data-id"),
            type_name: item.textContent.trim(),
            url: item.querySelector("a").href
        });
    });
    
    return {
        class: categories,
        page: 1,
        pagecount: 1
    };
}

// 处理视频列表（保持不变）
function handleVideoList(p, params) {
    const doc = new DOMParser().parseFromString(p, "text/html");
    const items = doc.querySelectorAll(".video-card");
    const list = [];
    
    items.forEach(item => {
        const titleEl = item.querySelector(".video-title");
        const imgEl = item.querySelector(".video-poster");
        const detailUrl = titleEl?.parentElement?.href;
        
        if (titleEl && imgEl && detailUrl) {
            list.push({
                name: titleEl.textContent.trim(),
                pic: imgEl.src,
                url: detailUrl,
                remark: item.querySelector(".video-meta")?.textContent || "",
                type: "video"
            });
        }
    });
    
    const totalText = doc.querySelector(".total-count")?.textContent || "0";
    const total = parseInt(totalText.match(/\d+/)[0]) || list.length;
    const pagecount = Math.ceil(total / 20);
    
    return {
        list: list,
        page: params.page || 1,
        pagecount: pagecount,
        total: total,
        limit: 20
    };
}

// 增强的播放地址处理函数
function handlePlayUrl(p, params) {
    try {
        // 1. 提取多线路播放地址
        const lines = extractPlayLines(p);
        
        if (lines.length === 0) {
            return { 
                error: "未找到播放地址",
                retry: true  // 允许重试
            };
        }
        
        // 2. 选择指定线路（默认第一条）
        const selectedLineIndex = params.lineIndex || 0;
        const selectedLine = lines[selectedLineIndex] || lines[0];
        
        // 3. 处理加密/特殊格式地址
        let finalUrl = selectedLine.url;
        if (finalUrl.includes("encrypted=")) {
            finalUrl = decryptUrl(finalUrl);  // 解密处理
        }
        
        // 4. 返回完整播放配置
        return {
            parse: 0,  // 0=直接播放, 1=需要二次解析
            url: finalUrl,
            line: selectedLine.name,
            lines: lines,  // 返回所有线路供选择
            headers: {
                "User-Agent": "Mozilla/5.0 (Linux; Android 10; ASUS_TV) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.181 TV Safari/537.36",
                "Referer": "https://www.asus-tv.com/",
                "Connection": "keep-alive"
            },
            // 新增播放参数配置
            playbackParams: {
                bufferTime: 10,  // 缓冲时间(秒)
                maxBitrate: "auto",  // 最大码率
                allowM3u8: true,  // 允许M3U8格式
                allowMp4: true    // 允许MP4格式
            },
            // 错误重试配置
            retryConfig: {
                maxRetries: 3,
                retryDelay: 2000  // 重试延迟(毫秒)
            }
        };
    } catch (e) {
        return {
            error: "播放地址解析失败: " + e.message,
            retry: true  // 允许重试
        };
    }
}

// 新增：提取多线路播放地址
function extractPlayLines(p) {
    const lines = [];
    const doc = new DOMParser().parseFromString(p, "text/html");
    
    // 1. 尝试从线路选择器提取
    const lineElements = doc.querySelectorAll(".play-line-item");
    if (lineElements.length > 0) {
        lineElements.forEach(el => {
            lines.push({
                name: el.textContent.trim(),
                url: el.getAttribute("data-url") || ""
            });
        });
    } 
    // 2. 尝试从JS变量提取
    else {
        const jsContent = doc.querySelector("script:contains('videoSources')")?.textContent;
        if (jsContent) {
            const sourcesMatch = jsContent.match(/videoSources\s*=\s*(\[.*?\])/);
            if (sourcesMatch && sourcesMatch[1]) {
                try {
                    const sources = JSON.parse(sourcesMatch[1]);
                    sources.forEach(src => {
                        lines.push({
                            name: src.name || `线路${lines.length + 1}`,
                            url: src.url || ""
                        });
                    });
                } catch (e) {
                    console.log("解析视频源失败:", e);
                }
            }
        }
    }
    
    // 3. 兜底线路（如果没有提取到）
    if (lines.length === 0) {
        const defaultUrl = p.match(/"videoUrl":"(https?:\/\/[^"]+)"/)?.[1] || "";
        if (defaultUrl) {
            lines.push({
                name: "默认线路",
                url: defaultUrl
            });
        }
    }
    
    return lines.filter(line => line.url);  // 过滤空地址
}

// 新增：解密URL（示例方法，根据实际加密方式修改）
function decryptUrl(encryptedUrl) {
    // 这里是示例解密逻辑，实际需根据目标网站的加密算法实现
    try {
        // 去除加密标记
        let url = encryptedUrl.replace("encrypted=", "");
        // Base64解码示例
        if (url.length % 4 > 0) {
            url += '='.repeat(4 - url.length % 4);
        }
        return atob(url);
    } catch (e) {
        console.log("URL解密失败，使用原始地址:", e);
        return encryptedUrl;
    }
}

// 新增：处理播放详情（如剧集列表）
function handlePlaybackInfo(p, params) {
    const doc = new DOMParser().parseFromString(p, "text/html");
    const episodes = [];
    
    // 提取剧集列表
    doc.querySelectorAll(".episode-item").forEach((item, index) => {
        episodes.push({
            name: item.textContent.trim() || `第${index + 1}集`,
            url: item.getAttribute("data-url") || params.detailUrl + "?ep=" + (index + 1),
            isCurrent: item.classList.contains("active"),  // 标记当前集
            episode: index + 1
        });
    });
    
    // 提取视频信息
    const videoInfo = {
        title: doc.querySelector(".video-title")?.textContent || "",
        description: doc.querySelector(".video-desc")?.textContent || "",
        duration: doc.querySelector(".video-duration")?.textContent || "",
        episodes: episodes,
        totalEpisodes: episodes.length
    };
    
    return {
        info: videoInfo,
        page: 1,
        pagecount: 1
    };
}

// 处理搜索功能（保持不变）
function handleSearch(p, params) {
    const doc = new DOMParser().parseFromString(p, "text/html");
    const items = doc.querySelectorAll(".search-result-item");
    const list = [];
    
    items.forEach(item => {
        const title = item.querySelector(".result-title")?.textContent || "";
        const url = item.querySelector("a")?.href || "";
        const pic = item.querySelector("img")?.src || "";
        
        if (title && url) {
            list.push({
                name: title,
                url: url,
                pic: pic,
                type: "video"
            });
        }
    });
    
    return {
        list: list,
        page: params.page || 1,
        pagecount: Math.ceil(list.length / 20),
        total: list.length
    };
}
